﻿//-----------------------------------------------------------------------
// <copyright file="SecurityController.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.UI.Web.Controllers{    using System;
    using System.Linq;
    using System.Web.Mvc;
    using AbstractSaaSTemplate.Application.Mvc;
    using AbstractSaaSTemplate.Domain.Models.Enumerators;
    using AbstractSaaSTemplate.Domain.Repositories;
    using AbstractSaaSTemplate.Domain.Services;
    using AbstractSaaSTemplate.UI.Web.Filters.Actions.Security;
    using AbstractSaaSTemplate.UI.Web.Helpers;
    using AbstractSaaSTemplate.UI.Web.Models.Security;

    /// <summary>
    /// Provides HTTP processing logic for the conceptual entity 'Security'
    /// in the 'Root' module of the application.
    /// </summary>
    public sealed class SecurityController : ApplicationController
    {
        /// <summary>
        /// Initializes a new instance of the SecurityController class
        /// injecting the services and repositories required for operation.
        /// </summary>
        /// <param name="serviceForMemberships">The service to consume 'Memberships'.</param>
        /// <param name="repositoryForMemberships">The repository to operate 'Memberships'.</param>
        public SecurityController(
            IMembershipService serviceForMemberships,
            IMembershipRepository repositoryForMemberships)
        {
            this.ServiceForMemberships = serviceForMemberships;
            this.RepositoryForMemberships = repositoryForMemberships;
        }

        /// <summary>
        /// Gets the service to consume 'Memberships'.
        /// </summary>
        public IMembershipService ServiceForMemberships { get; private set; }

        /// <summary>
        /// Gets the repository to operate 'Memberships'.
        /// </summary>
        public IMembershipRepository RepositoryForMemberships { get; private set; }
    
        /// <summary>
        /// GET: /Security/
        /// Provides a landing page for the 'Security' section of the area.
        /// </summary>
        /// <returns>Returns a view containing a landing page</returns>
        public ActionResult Index()
        {
            return this.Result();
        }

        /// <summary>
        /// GET: /Security/ManageRolesAccess
        /// Provides a create/edit features for the 'Security' section of the area.
        /// </summary>
        /// <returns>Returns a view containing a landing page</returns>
        [HttpGet]
        [FeatureAuthorization(
            AccessLevels.Distributor | AccessLevels.Tenant | AccessLevels.Account,
            ControlledFeatures.RolesFeaturesManagement,
            true)]
        public ActionResult ManageRolesAccess()
        {
            // we retrieve the active user so that we avoid
            // unnecessary processing to find it
            var activeUser = this.ServiceForMemberships.ActiveUser;

            // now we retrieve from the controlled features
            // all features that we have access to.
            var roleFeatures = this.RepositoryForMemberships.GetRoleFeaturesByAccessLevel(activeUser.AccessLevel);

            // retrieves the features
            var features = this.ServiceForMemberships.GetAllFeaturesForLevel(activeUser.AccessLevel)
                .Select(d => d.Feature)
                .ToArray();

            var model = new ManageRolesAccessForm(
                roleFeatures,
                features);

            return this.Result(model);
        }

        /// <summary>
        /// POST: /Security/ManageRolesAccess
        /// Processes the user input and try to proceed with the creation or edition of the item.
        /// </summary>
        /// <param name="input">The user input parsed into a form (view model) which can be used for easier validation of this data.</param>
        /// <returns>If validation or procedure fails, returns a view with errors loaded into the ModelState; otherwise redirects the user to the action "Index"</returns>
        [HttpPost]
        [FeatureAuthorization(
            AccessLevels.Distributor | AccessLevels.Account | AccessLevels.Tenant,
            ControlledFeatures.RolesFeaturesManagement)]
        [ValidateAntiForgeryToken]
        public ActionResult ManageRolesAccess(
            FormCollection input)
        {
            // we check the basic input and prevents null values for it
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            
            // we reinforce the model validation
            // this will ensure that the validation is performed
            // even when we are invoking this method from a unit test instead
            // of a HttpRequest.
            if (this.ModelState.IsValid)
            {
                this.TryValidateModel(input);
            }
            
            // we should validate all the data in the input argument
            // that could not be checked by the DataAnotations in the 'ManageRolesAccessForm'
            // add all errors using the this.ModelState.AddModelError() method
            
            /*
            this.ModelState.AddError(
                "Id",
                string.Format(
                    CultureInfo.CurrentCulture,
                    Messages.TheParameterXCannotBeNullOrWhiteSpace,
                    "Id"));
            */
            
            // we decide whether to proceed or not with the update operation
            // mostly by checking if the this.ModelState.IsValid
            if (this.ModelState.IsValid)
            {
                var activeUser = this.ServiceForMemberships.ActiveUser;
                
                var roleNames = Enum.GetNames(typeof(AccessRoles));
                foreach (var roleName in roleNames)
                {
                    var role = AccessRoles.None;
                    if (!Enum.TryParse<AccessRoles>(roleName, out role))
                    {
                        continue;
                    }

                    if (role == AccessRoles.None)
                    {
                        continue;
                    }

                    var featureNames = Enum.GetNames(typeof(ControlledFeatures));
                    foreach (var featureName in featureNames)
                    {
                        var feature = ControlledFeatures.None;
                        if (!Enum.TryParse<ControlledFeatures>(featureName, out feature))
                        {
                            continue;
                        }

                        if (feature == ControlledFeatures.None)
                        {
                            continue;
                        }

                        var fieldName = string.Concat(
                            roleName,
                            "-",
                            featureName);

                        if (input.AllKeys.Contains(fieldName))
                        {
                            this.RepositoryForMemberships.AssociateRoleWithFeature(
                                activeUser.AccessLevel,
                                role,
                                feature);
                        }
                        else
                        {
                            this.RepositoryForMemberships.RemoveAssociationBetweenRoleAndFeature(
                                activeUser.AccessLevel,
                                role,
                                feature);
                        }
                    }
                }
                
                // it was successfull, so we redirect
                // the user to "Security" > "Index"
                return this.RedirectToAction("ManageRolesAccess");
            }
                
            // we didn't manage to perform the operations
            // therefore we must return the default result
            // with model state information which explains
            // why we couldn't proceed.
            return this.Result(input);
        }
    }
}


